import Router from 'uni-router-interceptor'
import { getUserInfo } from 'API/login'

// import store from '../store/index'
import * as API from 'API/crm/message'
import store from '@/store/index.js'



/* import router from './index'
import store from '../store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({
	showSpinner: false
}) */
import {
	Message
} from 'element-ui'
/* import {
	getToken,
	removeToken
} from '@/utils/app' */





const router = new Router({
	homePage: '/pages/home/index'
})


// 路由白名单
const whiteList = [
	'/pages/login/index',
    '/pages/home/index',
	'/pages_personal/user',
	'/pages_message/messageIndex',
	'/pages_message/messageList',
	'/pages_message/messageDetail',
	 'pages_oa/notice/detail',
	'/pages/login/self',
	'/pages/login/sms',
	'/pages/login/setPwd',
	'/pages/login/register',
	'/pages/login/choose',
	'/pages_law/service',
	'/pages_law/privacy'
]

// 路由守卫
router.beforeEach((to, from, next) => {
	 let myToken = uni.getStorageSync('token');
	if (!myToken) {
		// 如果没有token跳转到登录
		uni.reLaunch('/pages/login/index')
	} else {
	// 如果有token开始判断roles[]有没有储存用户角色
			if (store.getters['user/roles'].length === 0) {
				// 如果没有储存
				store.dispatch('user/GetUserInfo').then(res => {
					console.log('路由token')
					
					// 开始获取用户的角色 动态分配路由权限
					store.dispatch('permission/GenerateRoutes').then(res => {
						console.log('分配权限')
						
						
					/* 	// 路由
						next({
							...to,
							replace: true
						})
						// 全局 币种 字典
						store.dispatch('app/GetCurrencyInfo').then(cres => {
							console.log('字典')
							if (cres.data.code == 0) {
								let currencyData = cres.data.data || [];
								let currencyObj = {};
								currencyData.forEach((item) => {
									currencyObj[item.code] = item.name;
								});
								store.dispatch('app/setCurrencyInfo', {list: currencyData, obj: currencyObj})
							}
						})
						// 全局 制造商 字典
						store.dispatch('app/GetMakerInfo').then(cres => {
							if (cres.data.code == 0) {
								let list = cres.data.data || [];
								let listObj = {};
								list.forEach((item) => {
									listObj[`${item.code}`] = item.name;
								});
								store.dispatch('app/setMakerInfo', {list: list, obj: listObj})
							}
						}) */
					})
				}).catch(err => {
					// TODO没必要用element ui，待改进
					Message.error(err.msg)
				})
			} else {
				// 如果已经获取了用户角色就写一部
				next();
			}
	} 
});

router.afterEach((to, from) => {
})

router.error(() => {
	if (process.env.NODE_ENV !== 'development') {
		router.reLaunch('/pages/home/index')
	}
})

export default router